﻿// Copyright (c) 2010 Dan Popick

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Media.Imaging;

using Open.Web.Stijl.Css;
using Open.Web.Stijl.Utility;

namespace Open.Web.Stijl
{
    public class Sprite: IDisposable
    {
		Bitmap _image;

        public string Url { get; set; }
        public string LocalPath { get; set; }
        public ColorHistogram ColorHistogram { get; set; }
        public PixelFormat Format { get; set; }
        public List<SpriteableRuleSet> RuleSets { get; set; }
		public RepeatType Repeat { get; set; }

        public Size Size { get; set; }
        public ColorSet Colors { get; set; }
        public Point Offset { get; set; }

        public DateTime FileTime { get; set; }
        
        public Sprite()
        {
            Colors = new ColorSet();
            RuleSets = new List<SpriteableRuleSet>();
        }

        public Sprite(SpriteableRuleSet ruleSet)
        {
            RuleSets = new List<SpriteableRuleSet>();
            RuleSets.Add(ruleSet);
            Colors = new ColorSet();
			Repeat = ruleSet.Repeat;
        }

        public Image GetImage()
        {
			if (_image != null)
				return _image;

            if (String.IsNullOrEmpty(LocalPath))
                throw new ArgumentException("LocalPath was not specified.");

			LoadImage(LocalPath);
            return _image;
        }

        public void LoadImage(string path)
        {
            LocalPath = path;
            _image = new Bitmap(LocalPath);

			Format = _image.PixelFormat;
			Size = _image.Size;
            Offset = Point.Empty;

            FileInfo fi = new FileInfo(LocalPath);
            FileTime = fi.LastWriteTimeUtc;

            // check for alpha colors
            bool hasAlpha = false;
            foreach (Color c in _image.Palette.Entries)
            {
                Colors.Add(c);
                hasAlpha |= c.A < 255;
            }

            // HACK: GIF can have indexed alpha colors. In that case, we fake a true color bitmap which 
            // will be merged in the Graphics object during the tiling process.
			if (hasAlpha && _image.PixelFormat.IsIndexed())
            {
                Format = PixelFormat.Format32bppArgb;
            }
        }

        public int ComputeQuickOverlap(Sprite s)
        {
            return ColorHistogram.ComputeOverlap(s.ColorHistogram);
        }

		public void Dispose()
		{
			if (_image != null)
				try
				{
					_image.Dispose();
				}
				catch { }
				finally
				{
					_image = null;
				}
		}
	}
}
